from urllib import request

import flask
from flask import Blueprint, session, jsonify

from controller.engine.weather import Weather

weather = Blueprint("weather", __name__)


@weather.route('/openweather')
def open_weather():
    return flask.render_template("openweather.html")


@weather.route("/save_location", methods=["POST"])
def save_location():
    data = flask.request.get_json()
    latitude = data.get('latitude')
    longitude = data.get('longitude')

    # 这里可以保存到数据库或进行其他操作
    print(f"收到定位数据 - 纬度: {latitude}, 经度: {longitude}")
    session["latitude"] = latitude
    session["longitude"] = longitude
    return jsonify({"status": "success", "message": "定位数据已接收"})


@weather.context_processor
def weather_data():
    global params
    if session.get("latitude") is None and session.get("latitude") is None:
        session["latitude"] = 31.238333
        session["longitude"] = 121.30555
    url = 'https://api.openweathermap.org/data/2.5/onecall'
    if session["latitude"] is not None and session["latitude"] is not None:
        params = '?lat=%s&lon=%s&appid=5796abbde9106b7da4febfae8c44c232&units=metric&lang=zh_cn&cnt=5' % (
            session["latitude"], session["longitude"])

    full_url = url + params
    headers = {
        "Accept": "* / *",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "Accept-Language": "en,zh-CN;q=0.9,zh;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "Connection": "keep - alive",
        "Host": "api.openweathermap.org",
        "Origin": "https: // openweathermap.org",
        "Referer": "https: // openweathermap.org /",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0"
    }
    try:
        req = request.Request(full_url, headers=headers)
        response = request.urlopen(req)
        data_handled = Weather().weather_data(response.read().decode("utf-8"))
        return dict(data=data_handled)
    except:
        return "定位数据不支持！"
